package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/*
* 骏伯
* */
@Slf4j
public class Plugin_ECARD_P045 implements ChannelService {


    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }

    /** 错误码 1，失败 0 异常 2 充值中
     * ("0", "成功"),
     * ("100","接收成功"), 2
     * ("1001", "参数错误"), 1  0
     * ("1002", "充值账号错误"), 1 0
     * ("1003", "请求过于频繁"),  重试
     * ("1004", "ip错误"),  重试 0 0
     * ("1007", "卡券标识id无效"),  1 0
     * ("1008", "预下单失败"),  重试 1 1
     * ("1009", "暂无此支付方式"),  重试 1 0
     * ("1010", "暂无此订单号信息"), 0 1
     * ("1011", "无效的订单号"), 1 1
     * ("1012", "抱歉！该类型兑换码已售罄"),1 1
     * ("1014", "渠道号错误"),  重试 1 0
     * ("1015", "产品费用规格错误"), 1 0
     * ("1016", "折扣券无效"),  1 0
     * ("1017", "您的操作太频繁了！"),  重试
     * ("1018", "产品ID错误"), 1 0
     * ("1019", "重复的订单号"),  重试
     * ("1020", "签名失败"),  重试 1 0
     * ("1021", "上游未返回充值信息"),  重试
     * ("1022", "商户余额不足"),  重试 1
     * ("1024","有效期内不可重复订购"),  重试 1
     * ("1025","充值号码充值次数超过当日限制次数"),  重试 1
     * ("0201", "产品未配置或获取不到产品信息"), 1
     * ("0202", "会员未充值/卡密未发送"); 0 2
     */

    // 提交订单
    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {

        try {
            HashMap<String, Object> params = new LinkedHashMap<>();
            String channelOrderCode = data.get("ChannelOrderCode").toString();
            String accountVal = data.get("AccountVal").toString();
            String SUPProductId = data.get("SUPProductId").toString();
            String partnerNo = apiConfig.getString("partnerNo"); // 商户号
            String backUrl = apiConfig.getString("backUrl"); // 回调地址
            String submitUrl = apiConfig.getString("SubmitUrl"); // 提交订单地址
            String key = apiConfig.getString("key"); // 密钥

            params.put("orderSEQ", channelOrderCode);
            params.put("phoneNo", accountVal);
            params.put("couponId", SUPProductId);
            params.put("partnerNo", partnerNo);

            String sign = generateSign(params, key);
            params.put("sign",sign);

            params.put("backUrl", backUrl);

            JSONObject res = JSONObject.parseObject(HttpTool.sendPost2(submitUrl, params));

            String code = res.getString("code");
            String msg = res.getString("msg");

            if (code == null){
                return ChannelResult.error(msg);
            }

            // 0 成功 1019 订单号重复 接收成功
            if ("0".equals(code) || "1019".equals(code) || "100".equals(code)){
                return ChannelResult.IN_PROCESS("充值中");
            } else if ("1004".equals(code) || "1003".equals(code) || "1017".equals(code) || "1010".equals(code)) {
                // 异常  ip错误 请求过于频繁  您的操作太频繁了  暂无此订单号信息
                return ChannelResult.error(msg);
            } else {
                // 失败
                return ChannelResult.FAILED(msg);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("骏伯提交订单接口错误：",e);
            return ChannelResult.error("骏伯提交订单接口错误");
        }
    }

    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {

        try {
            HashMap<String, Object> params = new LinkedHashMap<>();
            String channelOrderCode = data.get("ChannelOrderCode").toString();
            String partnerNo = apiConfig.getString("partnerNo"); // 商户号
            String QueryUrl = apiConfig.getString("QueryUrl"); // 查询订单地址
            String key = apiConfig.getString("key"); // 密钥

            params.put("orderSEQ", channelOrderCode);
            params.put("partnerNo", partnerNo);

            String sign = generateSign(params, key);
            params.put("sign",sign);

            JSONObject res = JSONObject.parseObject(HttpTool.sendPost2(QueryUrl, params));

            String code = res.getString("code");
            String msg = res.getString("msg");

            if (code == null){
                return ChannelResult.error(msg);
            }
            if ("0".equals(code)){
                return ChannelResult.success("充值成功");
            } else if ("1".equals(code) || "0202".equals(code)){
                // 会员未充值/卡密未发送
                return ChannelResult.IN_PROCESS("充值中");
            } else if ("1008".equals(code) || "1010".equals(code) || "1011".equals(code) || "1012".equals(code) || "1022".equals(code)
                    || "1024".equals(code) || "1025".equals(code) || "0201".equals(code) ) {
                // 预下单失败 暂无此订单号信息 无效的订单号 抱歉！该类型兑换码已售罄 商户余额不足 有效期内不可重复订购 充值号码充值次数超过当日限制次数 产品未配置或获取不到产品信息
                return ChannelResult.FAILED(msg);
            } else {
                return ChannelResult.error(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("骏伯查询订单接口错误：",e);
            return ChannelResult.error("骏伯查询订单接口错误");
        }

    }

    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");
    }

    // 基础md5加密
    public static String generateSign(Map<String, Object> params, String secret) throws NoSuchAlgorithmException {

        // Step : 将排序好的参数名和参数值拼装在一起
        StringBuilder sb = new StringBuilder();

        for (Map.Entry<String, Object> entry : params.entrySet()) {
            sb.append(entry.getKey()).append(entry.getValue());
        }
        // Step 3: 拼装字符串前后加上app的secret，然后进行MD5摘要
        sb.append("key").append(secret);
        System.out.println(sb);
        byte[] digest = MessageDigest.getInstance("MD5").digest(sb.toString().getBytes(StandardCharsets.UTF_8));

        // Step 4: 将摘要结果转换为十六进制表示
        StringBuilder signBuilder = new StringBuilder();
        for (byte b : digest) {
            String hex = Integer.toHexString(b & 0xff);
            if (hex.length() == 1) {
                signBuilder.append("0");
            }
            signBuilder.append(hex);
        }
        return signBuilder.toString();
    }
}
